import fs from 'fs'

fs.readFile('template.json', 'utf-8', (err, data) => {
  if (err) {
    throw err
  }

  const origin = JSON.parse(data).map((el) => {
    try {
      if (el.version !== '2') {
        return el
      }
      const _origin = JSON.parse(el.origin)
      _origin.createData.adcreative.baseInfo = {
        ..._origin.createData.adcreative.baseInfo,
        ads_set: _origin.createData.adcreative.baseInfo.ads_set || 'create',
        ad_format: _origin.createData.adcreative.baseInfo.ad_format || 'SINGLE_IMAGE_OR_VIDEO'
      }
      return {
        ...el,
        origin: JSON.stringify(_origin)
      }
    } catch (err) {
      console.log({ id: el.id, user_id: el.user_id, name: el.name })
      return el
    }
  })

  fs.writeFile('new_template.json', JSON.stringify(origin), (err) => {
    if (err) {
      throw err
    }
    console.log('JSON data is saved.')
  })
})
